package com.mes.cloud.base;

import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.logging.LoggingApplicationListener;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;

import java.util.Properties;

public class LoggingListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    public static final String SERVICE_NAME = "SERVICE_NAME";

    public static final String SERVICE_VERSION = "SERVICE_VERSION";

    public static final String SERVICE_HOST = "SERVICE_HOST";

    public static final String SERVICE_PORT = "SERVICE_PORT";

    public static final int DEFAULT_ORDER = LoggingApplicationListener.DEFAULT_ORDER - 1;


    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(event.getEnvironment());
        Properties properties = System.getProperties();

        String name = propertyResolver.getProperty("spring.application.name");
        if (!StringUtils.hasText(name)) {
            name = "UNKNOWN";
        }
        properties.setProperty(SERVICE_NAME, name);

        String version = propertyResolver.getProperty("spring.application.version");
        if (!StringUtils.hasText(version)) {
            version = "1.0.0";
        }
        properties.setProperty(SERVICE_VERSION, version);

        InetUtils inetUtils = new InetUtils(new InetUtilsProperties());
        properties.setProperty(SERVICE_HOST, inetUtils.findFirstNonLoopbackAddress().getHostAddress());

        String port = propertyResolver.getProperty("server.port");
        if (!StringUtils.hasText(port)) {
            port = "UNKNOWN";
        }
        properties.setProperty(SERVICE_PORT, port);
    }

    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }
}
